const del = require('del')
const gulp = require('gulp')
const gutil = require('gulp-util')
const oss = require('gulp-oss-sync')
const replace = require('gulp-replace')

// 运行的模式
const env = {}

// 获取用户配置
const config = require('./gulp.config')

// 日志输出
function log() {
  const args = Array.prototype.slice.call(arguments)
  gutil.log.apply(null, args)
}

// 上传h5的静态资源oss
function uploadH5OSS() {
  const h5Config = {
    assets: './src/unpackage/dist/build/h5/static/**',
    oss: {
      connect: {
        region: 'oss-cn-hangzhou',
        accessKeyId: 'LTAI5tC1wRCtas4aU1m4DxSP',
        accessKeySecret: 'B6qj7x5neN8fl5cOmcRiE6bOwhckmo',
        bucket: 'itaored'
      },
      controls: {
        'headers': {
          'Cache-Control': 'no-cache'
        }
      },
      setting: {
        dir: '/static/fed/m.itaored.com/v2.0.0/static', // 文件存储oss的对应路径
        noClean: false, // compare with the last cache file to decide if the file deletion is need
        force: true, // ignore cache file and force re-upload all the files
        quiet: true // quiet option for oss deleteMulti operation
      }
    }
  }
  log(`将静态资源目录${h5Config.assets}中的所有文件上传至OSS ${h5Config.oss.setting.dir}中...`)
  return gulp.src(h5Config.assets)
    .pipe(oss(h5Config.oss))
}

// clean
function clean() {
  return del(['dist', 'src/unpackage'])
}

// 关键字替换
function build() {
  const $config = env.CONFIG
  if ($config) {
    log('开始替换-> src/config/index.js')
    return gulp.src('src/config/index.js', { allowEmpty: true, base: 'src' })
      .pipe(replace(/project:.*?\,/g, () => {
        return `project: '${$config.project}',`
      }))
      .pipe(replace(/appName:.*?\,/g, () => {
        return `appName: '${$config.appName}',`
      }))
      .pipe(replace(/appId:.*?\,/g, () => {
        return `appId: '${$config.appId}',`
      }))
      .pipe(replace(/finderUserName:.*?\,/g, () => {
        return `finderUserName: '${$config.finderUserName}',`
      }))
      .pipe(replace(/srAppId:.*?\,/g, () => {
        return `srAppId: '${$config.srAppId}',`
      }))
      .pipe(replace(/\sserviceApi:.*?\,/g, () => {
        return ` serviceApi: '${$config.API}',`
      }))
      .pipe(replace(/\snodeApi:.*?\,/g, () => {
        return ` nodeApi: '${$config.nodeApi}',`
      }))
      .pipe(replace(/\sisOpen:.*?\,/g, () => {
        return ` isOpen: ${$config.isOpen || false},`
      }))
      .pipe(gulp.dest('dist'));
  } else {
    return new Error('配置文件为空')
  }
}

// manifest.json appid替换
function setManifest() {
  const $config = env.CONFIG
  console.log($config)
  if ($config) {
    log('开始替换-> manifest.json', $config.appId)
    return gulp.src('src/manifest.json', { allowEmpty: true, base: 'src' })
      .pipe(replace(/"mp-weixin"\s.*:\s.*\{\s.*"appid"\s.*:.*?",/gi, () => {
        return `"mp-weixin" : {
          "appid" : "${$config.appId}",`
      }))
      .pipe(replace(/"name"\s.*:\s.*?,\s.*"appid"\s.*:\s.*?",/gi, () => {
        return `"name" : "${$config.appName}",
          "appid" : "${$config.uniAppId}",`
      }))
      .pipe(gulp.dest('dist'));
  } else {
    return new Error('配置文件为空')
  }
}

// pages.json 关键字替换
function setPages() {
  const $config = env.CONFIG
  if ($config) {
    log('开始替换-> pages.json')
    return gulp.src('src/pages.json', { allowEmpty: true, base: 'src' })
      .pipe(replace(/99猫商城|和气/gi, () => {
        return $config.appName
      }))
      // 和气saas使用ext.json里的tabBar配置信息
      .pipe(replace(/"tabBar"(.*?)"globalStyle"/s, (a) => {
        if (['wx5801e8b7026b3df5', 'wxb3362041c4b65c27'].includes($config.appId)) {
          return `"globalStyle"`
        } else {
          return a
        }
      }))
      .pipe(gulp.dest('dist'));
  } else {
    return new Error('配置文件为空')
  }
}

// ext.json 关键字替换
function setExt() {
  const $config = env.CONFIG
  if ($config) {
    log('开始替换-> ext.json')
    return gulp.src('src/ext.json', { allowEmpty: true, base: 'src' })
      .pipe(replace(/"extAppid":\s.*?,/gi, () => {
        return `"extAppid": "${$config.appId}",`
      }))
      .pipe(replace(/"project":\s.*?,/gi, () => {
        return `"project": "${$config.project}",`
      }))
      .pipe(replace(/"appId":\s.*?,/gi, () => {
        return `"appId": "${$config.appId}",`
      }))
      .pipe(replace(/"serviceApi":\s.*?,/gi, () => {
        return `"serviceApi": "${$config.API}",`
      }))
      .pipe(replace(/"nodeApi":\s.*?,/gi, () => {
        return `"nodeApi": "${$config.nodeApi}",`
      }))
      .pipe(replace(/"storeId":\s.*?,/gi, () => {
        return `"storeId": ${$config.storeId || null},`
      }))
      .pipe(gulp.dest('dist'));
  } else {
    return new Error('配置文件为空')
  }
}

// uni.scss appid替换
function setScss() {
  const $config = env.CONFIG
  if ($config) {
    log('开始替换-> uni.scss', $config.appId)
    return gulp.src('src/uni.scss', { allowEmpty: true, base: 'src' })
      .pipe(replace(/\$appid:.*?\;/gi, () => {
        // 第三方平台与普通
        return `$appid: '${$config.isOpen ? $config.project : $config.appId}';`
      }))
      .pipe(gulp.dest('dist'));
  } else {
    return new Error('配置文件为空')
  }
}

// 从dist目录中把编译之后的文件覆盖到src中
function copy() {
  const $config = env.CONFIG
  log('执行结束-> ', $config.appId, $config.appName)
  return gulp.src('dist/**/*', { allowEmpty: true, base: 'dist' })
    .pipe(gulp.dest('src'));
}

// 上传oss
function uploadOSS() {
  log(`将静态资源目录${config.assets}中的所有文件上传至OSS CDN中... ${config.oss.setting.dir}中...`)
  return gulp.src(config.assets)
    .pipe(oss(config.oss))
}

// build:External-和气 - 抖音正式
async function setExternal () {
  return env.CONFIG = config.app.find(item => item.appId === 'wx7a0d6f560d5ac901')
}

// build:External-和气 - 抖音测试
async function setExternalTest () {
  return env.CONFIG = config.app.find(item => item.appId === 'wxdf9b01f4b35c7cb6')
}

// build:saasTest-和气 - saas测试
async function setSaasTest () {
  return env.CONFIG = config.app.find(item => item.appId === 'wxb3362041c4b65c27')
}

// build:saas-和气 - saas正式
async function setSaas () {
  return env.CONFIG = config.app.find(item => item.appId === 'wx5801e8b7026b3df5')
}
// 多多
async function setDDTest () {
  return env.CONFIG = config.app.find(item => item.appId === 'wx15ded090d215e20e')
}
async function setDD () {
  return env.CONFIG = config.app.find(item => item.appId === 'wx8c8be74424534a5a')
}
// 有茶有酒
async function setYc () {
  return env.CONFIG = config.app.find(item => item.appId === 'wx9e6b48f2aa0946ce')
}
// clean
exports['clean'] = gulp.series(clean)
// 小程序静态资源上传到oss
exports['upload:oss'] = gulp.series(uploadOSS)
// H5端静态资源上传到oss
exports['upload:oss h5'] = gulp.series(uploadH5OSS)
// 和气-抖音
exports['build:external'] = gulp.series(setExternal, clean, setManifest, setScss, setPages, setExt, build, copy)
exports['build:external-test'] = gulp.series(setExternalTest, clean, setManifest, setScss, setPages, setExt, build, copy)
// 和气-SAAS
exports['build:saas'] = gulp.series(setSaas, clean, setManifest, setScss, setPages, setExt, build, copy)
exports['build:saas-test'] = gulp.series(setSaasTest, clean, setManifest, setScss, setPages, setExt, build, copy)
// 多多来宝
exports['build:dd'] = gulp.series(setDD, clean, setManifest, setScss, setPages, setExt, build, copy)
exports['build:dd-test'] = gulp.series(setDDTest, clean, setManifest, setScss, setPages, setExt, build, copy)
exports['build:yc'] = gulp.series(setYc, clean, setManifest, setScss, setPages, setExt, build, copy)
